import cv2

image_np = cv2.imread('image.jpg')
image_np_grey = cv2.cvtColor(
    image_np,  # 要转换的图像
    cv2.COLOR_BGR2GRAY  # BGR→灰度
)
def THRESH_OTSU(data):
    list=[]
    for i in range(0,256):
        if i==0:
            continue
        else:
            n=0         #所有像素点数
            n0=0        #前景像素点数
            n1=0        #后景像素点数
            u=0         #整幅图的平均像素值
            u0=0        #前景的平均像素值
            u1=0        #后景的平均像素值
            for j in range(data.shape[0]):
                for k in range(data.shape[1]):
                    n+=1
                    u+=data[j, k]
                    if data[j, k] > i:
                         n0+=1
                         u0+=data[j, k]
                    else:
                        n1+=1
                        u1+=data[j, k]

            if n0==0 or n1==0:
                g=0
            else:
                u0 = u0 / n0
                u1=u1/n1
                w0 = n0 / n
                w1 = n1 / n
                u = u / n
                rows=data.shape[0]
                cols=data.shape[1]
                g=w0*(u0-u)**2+w1*(u1-u)**2     #每个像素值的g值
            list.append(g)
    T=list.index(max(list))+1
    return T
otsu=THRESH_OTSU(image_np_grey)# 阈值
maxval = 255  # 最大值
    # 二值化接口，返回值1是OSTU自动找到的阈值
    # 返回值2是处理的二值化图像
ret, image_np_threse = cv2.threshold(
    image_np_grey,  # 要处理灰度图
    otsu,  # 阈值
    maxval,  # 最大值
    cv2.THRESH_BINARY  # 反阈值法
)
print(f"OTSU找到的阈值:{otsu}")
cv2.imshow('image_np_therse', image_np_threse)
cv2.imwrite('image_np_therse.jpg', image_np_threse)
cv2.waitKey(0)
